import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter,asyncRouter,constantRoutes,anyRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles:[],
    buttons:[],
    routes:[],
    asRouter:[],
    //用户最终的路由
    resultAllRouters:[]
  }
}


const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO:(state,info)=>{
    state.name = info.name
    state.avatar = info.avatar
    state.routes = info.routes
    state.buttons = info.buttons
    state.roles = info.roles
  },
 ROUTES:(state,RouterInfo)=> {
  state.asRouter = RouterInfo
  state.resultAllRouters = constantRoutes.concat(state.asRouter,anyRouter)
  //添加新的路由
  router.addRoutes(state.resultAllRouters)
 }
} 

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    let result = await login({ username: username.trim(), password: password })
    if(result.code == 20000) {
      commit('SET_TOKEN', result.data.token)
      setToken(result.data.token)
      return 'ok'
    }else {
      return Promise.reject(new Error('faile'))
    }

  },

  // get user info
  async getInfo({ commit, state }) {
    let result = await getInfo(state.token)
    if(result.code == 20000) {
      if(!result.data) {
        return reject('Verification failed, please Login again.')
      }
      console.log(result);
    commit('SET_USERINFO',result.data)
      commit('ROUTES',comAcRoute(asyncRouter,result.data.routes))
      return 'ok'
    }else {
      return Promise.reject(new Error('falie'))
    }
    // return new Promise((resolve, reject) => {
    //   getInfo(state.token).then(response => {
    //     const { data } = response

    //     if (!data) {
    //       return reject('Verification failed, please Login again.')
    //     }

    //     const { name, avatar } = data

    //     commit('SET_NAME', name)
    //     commit('SET_AVATAR', avatar)
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  

  // user logout
  async logout({ commit, state }) {
    let result = await logout(state.token)
      if(result.code == 20000) {
        removeToken() 
        resetRouter()
        commit('RESET_STATE')
        return 'ok'
      }else {
        
      return Promise.reject(new Error('falie'))
    }
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     removeToken() // must remove  token  first
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

const comAcRoute=(asyncRouter,routes)=>{
  return asyncRouter.filter((item)=>{
    if(routes.indexOf(item.name)!= -1) {
      if(item.children && item.children.length) {
      item.children = comAcRoute(item.children,routes)
      }
      return true
    }
    
  })
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

